package cn.laixueit.service;

import cn.laixueit.commons.UserInfo;
import cn.laixueit.intercepter.MyIntercepter;
import cn.laixueit.pojo.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    private final String KEY = "user:cart:id:";

    public void addCart(Cart cart) {
        ThreadLocal<UserInfo> threadLocal = MyIntercepter.getThreadLocal();
        UserInfo userInfo = threadLocal.get();

        String key = KEY + userInfo.getId();
        BoundHashOperations<String, Object, Object> boundHash = redisTemplate.boundHashOps(key);

        // 判断当前用户的购物车中是否存在对应商品的数据
        Boolean boo = boundHash.hasKey(cart.getSkuId().toString());

        if(boo){
            Cart redisCart = (Cart) boundHash.get(cart.getSkuId().toString());
            redisCart.setNum(cart.getNum()+redisCart.getNum());
            cart = redisCart;
        }else{
            cart.setUserId(userInfo.getId());
        }
        boundHash.put(cart.getSkuId().toString(),cart);
    }

    public List<Cart> findCartList(){
        UserInfo userInfo = MyIntercepter.getThreadLocal().get();
        List<Cart> cartList  = redisTemplate.boundHashOps(KEY + userInfo.getId()).values();
        return  cartList;
    }
}
